package org.basis.algorithm.tree.practice;

import org.basis.algorithm.tree.common.TreeNode;

import java.util.HashMap;
import java.util.LinkedList;

/**
 * 求树的最大宽度
 *
 * @author Mr_wenpan@163.com 2021/12/22 14:20
 */
public class TreeMaxWidth2 {

    public static void main(String[] args) {

    }

    public static int getMaxWidth(TreeNode<Integer> head) {
        if (head == null) {
            return 0;
        }
        int curLevel = 1;
        int curCount = 1;
        int maxWidth = 1;
        // 用于记住每个节点所属的层
        HashMap<TreeNode<Integer>, Integer> levelMap = new HashMap<>();
        LinkedList<TreeNode<Integer>> queue = new LinkedList<>();
        queue.add(head);
        levelMap.put(head, 1);
        while (!queue.isEmpty()) {
            TreeNode<Integer> poll = queue.poll();
            TreeNode<Integer> left = poll.left;
            TreeNode<Integer> right = poll.right;
            // 该节点跨层了，结算上一层
            if (curLevel != levelMap.get(poll)) {
                curLevel++;
                maxWidth = Math.max(curCount, maxWidth);
                curCount = 1;
            } else {
                curCount++;
            }
            if (left != null) {
                queue.add(left);
                levelMap.put(left, levelMap.get(poll) + 1);
            }
            if (right != null) {
                queue.add(right);
                levelMap.put(right, levelMap.get(poll) + 1);
            }
        }

        return maxWidth;
    }
}
